﻿namespace MockingBird.Studio.UI
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.ServiceModel.Description;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml;
    using MockingBird.Studio.UI.Helpers;
    using MockingBird.Studio.UI.UserControls;
    using MockingBird.Studio.UI.UserControls.Model;
    using Thinktecture.Tools.Wscf.Services.ServiceDescription.Contract;

    public partial class MessageBuilder : ComponentFactory.Krypton.Toolkit.KryptonForm
    {
        private ServiceDefinition serviceDefinition;

        #region "Constructor(s)"
        public MessageBuilder()
        {
            InitializeComponent();
            this.tvwWsdlBrowser.WsdlMenuClicked += new WsdlTreeEventHandler(WsdlMenuItemClicked);
        }

        #endregion

        #region "event handlers"

        private void HandleFormLoad()
        {
            txtWsdlUrl.Text = ConfigurationManager.AppSettings["default_wsdl_location"];
            InitializeDialogProperties();
        }

        private void WsdlMenuItemClicked(object sender, WsdlTreeEventArgs e)
        {
            this.ProcessCommandActions(e.Command, e.ItemName);
        }

        #endregion

        #region "helper methods"

        private void InitializeDialogProperties()
        {
            //Sets up the default properties for the dialogs. In future versions
            // this may read config settings for the same

            // WSDL Browse Dialog
            dlgWsdlBrowse.DefaultExt = "*.wsdl";
            dlgWsdlBrowse.Filter = "WSDL files (*.wsdl)|*.wsdl";
            dlgWsdlBrowse.FileName = "";
            dlgWsdlBrowse.InitialDirectory = Path.GetDirectoryName(txtWsdlUrl.Text);

            // Sample message SAVE-AS dialog
            dlgSaveMessageToFile.AddExtension = true;  // automatically add the xml extension
            //dlgSaveMessageToFile.DefaultExt = "*.xml";
            dlgSaveMessageToFile.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";


        }

        private void LoadWsdl()
        {
            try
            {
                string wsdlUrl = txtWsdlUrl.Text;
                this.serviceDefinition = MetadataHelper.ImportWsdl(wsdlUrl);
                WsdlDocumentCommands commands = this.GetWsdlCommands();
                this.tvwWsdlBrowser.LoadTree(this.serviceDefinition, commands);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
                txtWsdlUrl.Focus();
                return;
            }
        }

        private void SaveMessage()
        {
            string msgFileName = String.Empty;

            DialogResult result = dlgSaveMessageToFile.ShowDialog();
            if (result == DialogResult.OK)
            {
                msgFileName = dlgSaveMessageToFile.FileName;
            }
            if (!String.IsNullOrEmpty(msgFileName))
            {
                File.AppendAllText(msgFileName, txtMessage.Text, Encoding.UTF8);
                MessageBox.Show("Successfully saved contents to file : " + msgFileName);
            }
        }

        private WsdlDocumentCommands GetWsdlCommands()
        {
            WsdlDocumentCommands commands = new WsdlDocumentCommands();
            commands.MessageCommands = new List<CommandAction>();

            // Should load from configuration. for now we set the standard data

            CommandAction generateSample = new CommandAction();
            generateSample.CommandName = "GenerateSample";
            generateSample.DisplayName = "GenerateSample";
            generateSample.Action = "GenerateSample";
            commands.MessageCommands.Add(generateSample);

            CommandAction dummy = new CommandAction();
            dummy.CommandName = dummy.DisplayName = dummy.Action = "Dummy";
            commands.MessageCommands.Add(dummy);

            return commands;
        }

        private void ProcessCommandActions(CommandAction action, string itemName)
        {
            switch (action.CommandName)
            {
                case "GenerateSample":
                    this.GenerateSampleMessage(itemName);
                    break;

                default:
                    break;
            }
        }

        private void GenerateSampleMessage(string messageName)
        {

            MessageDescription locatedMsg = this.serviceDefinition.FindMessage(messageName);
            if (locatedMsg == null)
            {
                MessageBox.Show(string.Format("Could not find a message named {0} in service definition", messageName));
                return;
            }

            try
            {
                XmlDocument xDoc = MessageHelper.GenerateInstance(locatedMsg, this.serviceDefinition.SchemaSet);
                txtMessage.Text = xDoc.OuterXml;
            }
            catch (Exception ex)
            {
                txtMessage.Text = "Could not generate instance document. " + ex.ToString();
                return;
            }

        }

        #endregion
    }
}
